const fs = require('fs').promises;
const path = require('path');

class PluginManager {
    constructor(config) {
        this.config = config;
        this.plugins = new Map();
        this.pluginStats = new Map();
        this.enabledPlugins = new Set();
    }

    /**
     * 自动扫描并加载所有插件
     */
    async autoLoadPlugins() {
        const pluginsDir = path.join(__dirname, '../plugins');
        
        try {
            const files = await fs.readdir(pluginsDir);
            const pluginFiles = files.filter(file => 
                file.endsWith('.js') && file !== 'base-plugin.js'
            );

            console.log(`🔍 发现 ${pluginFiles.length} 个插件文件`);

            for (const file of pluginFiles) {
                await this.loadPlugin(path.join(pluginsDir, file));
            }

            // 按优先级排序
            this.sortPluginsByPriority();
            
            console.log(`✅ 成功加载 ${this.enabledPlugins.size}/${this.plugins.size} 个插件`);
            
        } catch (error) {
            console.log(`❌ 扫描插件目录失败: ${error.message}`);
        }
    }

    /**
     * 加载单个插件并进行健康检查
     */
    async loadPlugin(pluginPath) {
        try {
            const PluginClass = require(pluginPath);
            const plugin = new PluginClass();
            const pluginName = plugin.name || path.basename(pluginPath, '.js');

            // 基础验证
            if (!this.validatePlugin(plugin)) {
                console.log(`❌ 插件 ${pluginName} 验证失败`);
                return false;
            }

            // 设置消息发送器引用
            if (this.messageSender) {
                plugin.messageSender = this.messageSender;
            }

            // 健康检查
            const isHealthy = await plugin.healthCheck();
            plugin.enabled = isHealthy;

            // 注册插件
            this.plugins.set(pluginName, plugin);
            this.pluginStats.set(pluginName, {
                loadTime: new Date(),
                callCount: 0,
                successCount: 0,
                errorCount: 0,
                lastError: null
            });

            if (isHealthy) {
                this.enabledPlugins.add(pluginName);
                
                // 执行初始化
                if (plugin.onInit) {
                    await plugin.onInit();
                }
                
                console.log(`✅ 加载插件: ${pluginName} v${plugin.version} (优先级:${plugin.priority})`);
            } else {
                console.log(`⚠️ 插件 ${pluginName} 健康检查失败，已禁用`);
            }

            return isHealthy;

        } catch (error) {
            console.log(`❌ 加载插件失败 ${pluginPath}: ${error.message}`);
            return false;
        }
    }

    /**
     * 插件基础验证
     */
    validatePlugin(plugin) {
        const requiredProps = ['name', 'version', 'priority'];
        const requiredMethods = ['onPrivateMessage', 'onGroupMessage'];

        // 检查必要属性
        for (const prop of requiredProps) {
            if (!plugin[prop]) {
                console.log(`❌ 插件缺少必要属性: ${prop}`);
                return false;
            }
        }

        // 检查必要方法
        for (const method of requiredMethods) {
            if (typeof plugin[method] !== 'function') {
                console.log(`❌ 插件缺少必要方法: ${method}`);
                return false;
            }
        }

        // 检查优先级范围
        if (plugin.priority < 1 || plugin.priority > 100) {
            console.log(`❌ 插件优先级超出范围 (1-100): ${plugin.priority}`);
            return false;
        }

        return true;
    }

    /**
     * 按优先级排序插件
     */
    sortPluginsByPriority() {
        const sorted = Array.from(this.plugins.entries())
            .sort(([, a], [, b]) => b.priority - a.priority);
        
        this.plugins = new Map(sorted);
    }

    /**
     * 处理事件（支持优先级和统计）
     */
    async handleEvent(payload, messageSender) {
        const results = {
            handled: false,
            handledBy: null,
            responses: [],
            errors: []
        };

        // 按优先级顺序调用启用的插件
        for (const [name, plugin] of this.plugins) {
            if (!plugin.enabled) continue;

            const stats = this.pluginStats.get(name);
            stats.callCount++;

            try {
                const result = await this.callPluginHandler(plugin, payload, messageSender);
                
                if (result && result.handled) {
                    results.handled = true;
                    results.handledBy = name;
                    stats.successCount++;

                    if (result.response) {
                        results.responses.push({
                            plugin: name,
                            response: result.response
                        });
                    }

                    // 如果插件处理了事件且不继续传播，则停止
                    if (!result.continuePropagation) {
                        break;
                    }
                }

            } catch (error) {
                stats.errorCount++;
                stats.lastError = error.message;
                results.errors.push({
                    plugin: name,
                    error: error.message
                });
                console.log(`💥 插件 ${name} 执行错误: ${error.message}`);
            }
        }

        return results;
    }

    async callPluginHandler(plugin, payload, messageSender) {
        const { post_type, message_type, notice_type, request_type, sub_type } = payload;

        // 创建回复函数
        const createReply = (targetId, isGroup = false) => {
            return async (text) => {
                try {
                    if (isGroup) {
                        return await messageSender.sendGroupMessage(targetId, text);
                    } else {
                        return await messageSender.sendPrivateMessage(targetId, text);
                    }
                } catch (error) {
                    console.log(`💥 回复失败: ${error.message}`);
                }
            };
        };

        // 创建审批函数
        const createApprove = (flag, requestType) => {
            return async (approve = true, remark = '') => {
                try {
                    if (requestType === 'friend') {
                        return await messageSender.setFriendAddRequest(flag, approve, remark);
                    } else {
                        return await messageSender.setGroupAddRequest(flag, sub_type, approve, remark);
                    }
                } catch (error) {
                    console.log(`💥 审批操作失败: ${error.message}`);
                }
            };
        };

        // 根据事件类型调用对应处理器
        switch (post_type) {
            case 'message':
                if (message_type === 'private') {
                    return await plugin.onPrivateMessage(payload, createReply(payload.user_id, false));
                } else if (message_type === 'group') {
                    return await plugin.onGroupMessage(payload, createReply(payload.group_id, true));
                }
                break;

            case 'message_sent':
                const isGroup = !!payload.group_id;
                const targetId = payload.user_id || payload.group_id;
                return await plugin.onMessageSent(payload, createReply(targetId, isGroup));

            case 'notice':
                switch (notice_type) {
                    case 'group_upload':
                        return await plugin.onGroupUpload(payload, createReply(payload.group_id, true));
                    case 'group_admin':
                        return await plugin.onGroupAdminChange(payload, createReply(payload.group_id, true));
                    case 'group_decrease':
                        return await plugin.onGroupMemberDecrease(payload, createReply(payload.group_id, true));
                    case 'group_increase':
                        return await plugin.onGroupMemberIncrease(payload, createReply(payload.group_id, true));
                    case 'group_ban':
                        return await plugin.onGroupBan(payload, createReply(payload.group_id, true));
                    case 'friend_add':
                        return await plugin.onFriendAdd(payload, createReply(payload.user_id, false));
                    case 'group_recall':
                        return await plugin.onGroupRecall(payload, createReply(payload.group_id, true));
                    case 'friend_recall':
                        return await plugin.onFriendRecall(payload, createReply(payload.user_id, false));
                    case 'group_card':
                        return await plugin.onGroupCardChange(payload, createReply(payload.group_id, true));
                    case 'offline_file':
                        return await plugin.onOfflineFile(payload, createReply(payload.user_id, false));
                    case 'client_status':
                        return await plugin.onClientStatusChange(payload, createReply());
                    case 'essence':
                        return await plugin.onEssenceMessageChange(payload, createReply(payload.group_id, true));
                    case 'notify':
                        return await plugin.onNotify(payload, createReply(payload.group_id || payload.user_id, !!payload.group_id));
                    case 'group_title':
                        return await plugin.onGroupTitleChange(payload, createReply(payload.group_id, true));
                    case 'group_lucky_king':
                        return await plugin.onGroupLuckyKing(payload, createReply(payload.group_id, true));
                    case 'group_honor':
                        return await plugin.onGroupHonorChange(payload, createReply(payload.group_id, true));
                }
                break;

            case 'request':
                if (request_type === 'friend') {
                    return await plugin.onFriendRequest(payload, createApprove(payload.flag, 'friend'));
                } else if (request_type === 'group') {
                    return await plugin.onGroupRequest(payload, createApprove(payload.flag, 'group'));
                }
                break;

            case 'meta_event':
                if (meta_event_type === 'lifecycle') {
                    return await plugin.onLifecycle(payload, createReply());
                } else if (meta_event_type === 'heartbeat') {
                    return await plugin.onHeartbeat(payload, createReply());
                }
                break;
        }

        return { handled: false };
    }

    /**
     * 设置消息发送器
     */
    setMessageSender(messageSender) {
        this.messageSender = messageSender;
        // 为所有已加载的插件设置消息发送器
        for (const [name, plugin] of this.plugins) {
            plugin.messageSender = messageSender;
        }
    }

    /**
     * 获取所有插件信息
     */
    getAllPluginsInfo() {
        const pluginsInfo = [];
        
        for (const [name, plugin] of this.plugins) {
            pluginsInfo.push({
                ...plugin.getInfo(),
                stats: this.pluginStats.get(name)
            });
        }
        
        return pluginsInfo;
    }

    /**
     * 获取全局帮助信息
     */
    getGlobalHelp() {
        const help = {
            enabledPlugins: this.enabledPlugins.size,
            totalPlugins: this.plugins.size,
            commands: []
        };

        // 收集所有启用的插件的命令
        for (const [name, plugin] of this.plugins) {
            if (plugin.enabled && plugin.commands && plugin.commands.size > 0) {
                help.commands.push({
                    plugin: name,
                    commands: Array.from(plugin.commands.entries()).map(([cmd, info]) => ({
                        command: cmd,
                        description: info.description,
                        usage: info.usage,
                        example: info.example
                    }))
                });
            }
        }

        return help;
    }

    /**
     * 启用/禁用插件
     */
    setPluginEnabled(pluginName, enabled) {
        const plugin = this.plugins.get(pluginName);
        if (plugin) {
            plugin.enabled = enabled;
            if (enabled) {
                this.enabledPlugins.add(pluginName);
            } else {
                this.enabledPlugins.delete(pluginName);
            }
            return true;
        }
        return false;
    }

    /**
     * 获取统计信息
     */
    getStats() {
        return {
            totalPlugins: this.plugins.size,
            enabledPlugins: this.enabledPlugins.size,
            pluginStats: Object.fromEntries(this.pluginStats)
        };
    }
}

module.exports = PluginManager;